import * as gpio from 'gpio';
import * as uart from 'uart';
import * as adc  from 'adc';
import * as fs from 'fs';
import * as audioPlayer from 'audioplayer';

var  mainplayerHandle = new audioPlayer.audioPlayer();
mainplayerHandle.setVolume(3);
mainplayerHandle.play('/jsamp/welcomehaas.wav', function() {
	console.log('audio played')
});

 /* string convert to decimal array*/
 function StrToDecArray(str) {
	var obj = {
		'0':48,
		'1':49,
		'2':50,
		'3':51,
		'4':52,
		'5':53,
		'6':54,
		'7':55,
		'8':56,
		'9':57,
	}
	return str.split('').map(function(i) {
		if(obj[i]) {
			return obj[i]
		}
		return i.charCodeAt()
	})
}

 /* array buffer convert to string */
 function ab2str(buf) {
	return String.fromCharCode.apply(null, new Uint8Array(buf));
}

/* array buffer convert to array */
function ab2arr(buf) {
	return Array.prototype.slice.call(new Uint8Array(buf));
}


var led = gpio.open({
	id: 'USER_LED'
});

/* GPIO init */
var GPIO1 = gpio.open({
	id: 'IO1'
});
var GPIO2 = gpio.open({
	id: 'IO2'
});
var GPIO3 = gpio.open({
	id: 'IO3'
});
var GPIO4 = gpio.open({
	id: 'IO4'
});

GPIO1.writeValue(0);	// GPIO output 0
GPIO2.writeValue(1);	// GPIO output 1
GPIO3.writeValue(1);	// GPIO output 1
GPIO4.writeValue(1);	// GPIO output 1

 /* open mainuart */
 var serial1 = uart.open({
	id: 'mainuart',
	success: function() {
		console.log('open main_uart success')
	},
	fail: function() {
		console.log('open main_uart fail')
	}
});

 /* open ex_uart */
 /* if use ex_uart please disable GPIO1 and GPIO2 */
//  var serial2 = uart.open({
// 	id: 'uartex',
// 	success: function() {
// 		console.log('open ex_uart success')
// 	},
// 	fail: function() {
// 		console.log('open ex_uart fail')
// 	}
// });


 /* open adc */
var adc0 = adc.open({
	id: 'ADC0',
	success: function() {
	  console.log('adc: open adc0 success')
	},
	fail: function() {
	  console.log('adc: open adc0 failed')
	}
  });

setInterval(function () {
	 led.toggle();	// user led toggled
	 // if use ex_uart please don`t operate GPIO1 & GPIO2
	 GPIO1.toggle();
	 GPIO2.toggle();
	 // if use ex_uart please don`t operate GPIO1 & GPIO2
	 GPIO3.toggle();
	 GPIO4.toggle();
	// get adc value and print to console
	 console.log('adc: adc1 value ' + adc0.readValue()*2 + ' mV')
	 // send data to uart
	 serial1.write(StrToDecArray('hello world main uart\r\n'));
	//  serial2.write(StrToDecArray('hello world ex uart\r\n'));
 }, 1000);
 // if uart recevice data will callback
serial1.on('data', function(data) {
    console.log('main uart recv data: ' + ab2str(data));	// conver to string to print
	var rec_data = ab2arr(data)   // conver arraybuffer to array
	if(rec_data[0] > 20){
		console('To show you how to use data');
	}
})

// serial2.on('data', function(data) {
//     console.log('main uart recv data: ' + ab2str(data));
// })



